//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.linln.admin.gdp.controller;

import com.linln.admin.gdp.validator.RegionGdpValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.exception.ResultException;
import com.linln.common.jpahelper.BaseCriteria;
import com.linln.common.jpahelper.Criteria;
import com.linln.common.jpahelper.Restrictions;
import com.linln.common.utils.DateUtil;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.utils.StringUtil;
import com.linln.common.vo.ResultVo;
import com.linln.component.excel.ExcelReader;
import com.linln.component.excel.ExcelUtil;
import com.linln.component.fileUpload.FileUpload;
import com.linln.component.fileUpload.enums.UploadResultEnum;
import com.linln.component.jwt.annotation.IgnorePermissions;
import com.linln.component.thymeleaf.utility.DictUtil;
import com.linln.modules.api.exceptions.ProjectMatchException;
import com.linln.modules.gdp.domain.RegionGdp;
import com.linln.modules.gdp.service.RegionGdpService;
import com.linln.modules.gdp.service.impl.RegionGdpServiceImpl;
import com.linln.modules.system.domain.Upload;
import com.linln.modules.system.service.UploadService;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.ExampleMatcher.MatcherConfigurer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping({"/gdp/regionGdp"})
public class RegionGdpController {
    @Autowired
    private RegionGdpService regionGdpService;
    @Autowired
    private UploadService uploadService;
    private static int FIELD_ROW = 0;

    public RegionGdpController() {
    }

    @GetMapping({"/index"})
    @RequiresPermissions({"gdp:regionGdp:index"})
    public String index(Model model, RegionGdp regionGdp) {
        ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("name", (match) -> {
            match.contains();
        }).withMatcher("city", (match) -> {
            match.contains();
        }).withMatcher("checkName", (match) -> {
            match.contains();
        }).withMatcher("reviewStatus", (match) -> {
            match.contains();
        });
        Example<RegionGdp> example = Example.of(regionGdp, matcher);
        Page<RegionGdp> list = this.regionGdpService.getPageList(example);
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/gdp/regionGdp/index";
    }

    @GetMapping({"/add"})
    @RequiresPermissions({"gdp:regionGdp:add"})
    public String toAdd() {
        return "/gdp/regionGdp/add";
    }

    @GetMapping({"/edit/{id}"})
    @RequiresPermissions({"gdp:regionGdp:edit"})
    public String toEdit(@PathVariable("id") RegionGdp regionGdp, Model model) {
        model.addAttribute("regionGdp", regionGdp);
        return "/gdp/regionGdp/add";
    }

    @PostMapping({"/save"})
    @RequiresPermissions({"gdp:regionGdp:add", "gdp:regionGdp:edit"})
    @ResponseBody
    public ResultVo save(@Validated RegionGdpValid valid, RegionGdp regionGdp) {
        if (regionGdp.getId() != null) {
            RegionGdp beRegionGdp = this.regionGdpService.getById(regionGdp.getId());
            EntityBeanUtil.copyProperties(beRegionGdp, regionGdp);
        }

        //设置状态
        String checkStatus= regionGdp.getCheckStatus();
        if(checkStatus.equals("技审通过"))
            regionGdp.setReviewStatus("是");
        this.regionGdpService.save(regionGdp);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    @GetMapping({"/detail/{id}"})
    @RequiresPermissions({"gdp:regionGdp:detail"})
    public String toDetail(@PathVariable("id") RegionGdp regionGdp, Model model) {
        model.addAttribute("regionGdp", regionGdp);
        return "/gdp/regionGdp/detail";
    }

    @RequestMapping({"/status/{param}"})
    @RequiresPermissions({"gdp:regionGdp:status"})
    @ResponseBody
    public ResultVo status(@PathVariable("param") String param, @RequestParam(value = "ids",required = false) List<Long> ids) {
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        return this.regionGdpService.updateStatus(statusEnum, ids) ? ResultVoUtil.success(statusEnum.getMessage() + "成功") : ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
    }

    @GetMapping({"/import"})
    @RequiresPermissions({"gdp:regionGdp:add"})
    @IgnorePermissions
    public String match() {
        return "/gdp/regionGdp/import";
    }

    @PostMapping({"/upload"})
    @ResponseBody
    public ResultVo uploadGdpFile(@RequestParam("gdpFile") MultipartFile multipartFile) {
        Upload upload = FileUpload.getFile(multipartFile, "/gdpFile");

        try {
            String[] types = new String[]{"application/vnd.ms-excel"};
            if (!FileUpload.isContentType(multipartFile, types)) {
                throw new ResultException(UploadResultEnum.NO_FILE_TYPE);
            } else {
                Upload uploadSha1 = this.uploadService.getBySha1(FileUpload.getFileSha1(multipartFile));
                if (uploadSha1 != null) {
                    return ResultVoUtil.success(uploadSha1);
                } else {
                    FileUpload.transferTo(multipartFile, upload);
                    this.uploadService.save(upload);
                    return ResultVoUtil.success(upload);
                }
            }
        } catch (NoSuchAlgorithmException | IOException var5) {
            return ResultVoUtil.error("上传GDP文件失败");
        }
    }

    @PostMapping({"/findGdpByYear"})
    @ResponseBody
    public ResultVo findGdpByNames(@RequestParam("name") String name) {
        List<RegionGdp> existGdps = this.regionGdpService.findByName(name);
        return ResultVoUtil.success(existGdps);
    }

    @GetMapping({"/findAllYears"})
    @ResponseBody
    public ResultVo findAllNames() {
        List<Map<String, String>> years = this.regionGdpService.findAllNames();
        return ResultVoUtil.success(years);
    }

    @PostMapping({"/excImport"})
    @ResponseBody
    public ResultVo excImport(@RequestParam("upFileId") String upFileId) {
        Upload upload = this.uploadService.getById(Long.valueOf(upFileId));
        String basePath = FileUpload.getUploadPath();
        String absUrl = basePath.substring(0, basePath.length() - 8) + upload.getPath();
        File file = new File(absUrl);
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(file);
            ExcelReader reader = new ExcelReader();
            boolean isOffice2003 = ExcelReader.isExcel2003(file.getName());
            List<List<String>> rows = reader.read(fis, isOffice2003);
            Map<String, Integer> fieldMap = this.getFieldMap(rows, FIELD_ROW);
            List<RegionGdp> inGdps = this.parseRegionGdps("", rows, fieldMap);
            StringBuffer validMsg = this.regionGdpService.validRegionGdp(inGdps);
            if (validMsg.length() > 0) {
                return ResultVoUtil.error(validMsg.toString());
            } else {
                this.regionGdpService.exeImport(inGdps);
                return ResultVoUtil.success("数据导入成功");
            }
        } catch (ProjectMatchException var13) {
            var13.printStackTrace();
            return ResultVoUtil.error(var13.getMessage());
        } catch (FileNotFoundException var14) {
            var14.printStackTrace();
            return ResultVoUtil.error("数据导入失败");
        }
    }

    private Map<String, Integer> getFieldMap(List<List<String>> rows, int titleRow) {
        Map<String, Integer> fieldMap = new HashMap();
        List<String> fields = (List)rows.get(titleRow);

        for(int i = 0; i < fields.size(); ++i) {
            String field = (String)fields.get(i);
            fieldMap.put(field, i);
        }

        return fieldMap;
    }

    private List<RegionGdp> parseRegionGdps(String year, List<List<String>> rows, Map<String, Integer> fieldMap) {
        List<RegionGdp> gdps = new ArrayList();

        for(int i = RegionGdpServiceImpl.DATA_START_ROW; i < rows.size(); ++i) {
            List<String> cells = (List)rows.get(i);
            RegionGdp gdp = new RegionGdp();
            Field[] fields = gdp.getClass().getDeclaredFields();

            for(int j = 0; j < fields.length; ++j) {
                Field field = fields[j];
                String fieldName = field.getName();
                if (fieldMap.containsKey(fieldName)) {
                    int cIndex = (Integer)fieldMap.get(fieldName);
                    Object value = cells.get(cIndex);
                    this.setField(gdp, field, value);
                }
            }

            gdps.add(gdp);
        }

        return gdps;
    }

    private void setField(RegionGdp gdp, Field field, Object fieldValue) {
        try {
            Class clz = gdp.getClass();
            String name = field.getName();
            name = name.substring(0, 1).toUpperCase() + name.substring(1);
            String type = field.getGenericType().toString();
            Method m;
            if (type.equals("class java.lang.String") && fieldValue != null) {
                String value = (String)fieldValue;
                m = clz.getMethod("set" + name, String.class);
                m.invoke(gdp, value);
            }

            if (type.equals("class java.lang.Integer") && fieldValue != null && !StringUtil.isEmpty(fieldValue.toString())) {
                Integer value = Integer.parseInt(fieldValue.toString());
                m = clz.getMethod("set" + name, Integer.class);
                m.invoke(gdp, value);
            }

            if (type.equals("class java.lang.Double") && fieldValue != null && !StringUtil.isEmpty(fieldValue.toString())) {
                Double value = Double.parseDouble(fieldValue.toString());
                m = clz.getMethod("set" + name, Double.class);
                m.invoke(gdp, value);
            }

            if (type.equals("class java.lang.Boolean") && fieldValue != null && !StringUtil.isEmpty(fieldValue.toString())) {
                Boolean value = Boolean.parseBoolean(fieldValue.toString());
                m = clz.getMethod("set" + name, Boolean.class);
                m.invoke(gdp, value);
            }

            if (type.equals("class java.util.Date") && fieldValue != null && !StringUtil.isEmpty(fieldValue.toString())) {
                Date value = DateUtil.fromString(fieldValue.toString());
                m = clz.getMethod("set" + name, Date.class);
                m.invoke(gdp, value);
            }
        } catch (NoSuchMethodException var9) {
            var9.printStackTrace();
        } catch (SecurityException var10) {
            var10.printStackTrace();
        } catch (IllegalAccessException var11) {
            var11.printStackTrace();
        } catch (IllegalArgumentException var12) {
            var12.printStackTrace();
        } catch (InvocationTargetException var13) {
            var13.printStackTrace();
        }

    }



    /**
     * 导出用户数据
     */
    @GetMapping("/export")
    @RequiresPermissions({"gdp:regionGdp:export"})
    @ResponseBody
    public void exportExcel(
            @RequestParam(value ="name",required = false) String name,
            @RequestParam(value ="city",required = false) String city,
            @RequestParam(value ="applyItem",required = false) String applyItem,
            @RequestParam(value ="reviewStatus",required = false) String reviewStatus,
            @RequestParam(value ="checkStatus",required = false) String checkStatus,
            @RequestParam(value ="checkName",required = false) String checkName
){
        Criteria<RegionGdp> criteria=new BaseCriteria<>();
        if(!StringUtil.isEmpty(name)){
            criteria.addAnd(Restrictions.eq("name",name));
        }

        if(!StringUtil.isEmpty(city)){
            criteria.addAnd(Restrictions.eq("city",city));
        }

        if(!StringUtil.isEmpty(applyItem)){
            criteria.addAnd(Restrictions.eq("applyItem",applyItem));
        }

        if(!StringUtil.isEmpty(reviewStatus)){
            criteria.addAnd(Restrictions.eq("reviewStatus",reviewStatus));
        }

        if(!StringUtil.isEmpty(checkName)){
            criteria.addAnd(Restrictions.eq("checkName",checkName));
        }
        List<RegionGdp> exsitGdps=regionGdpService.findByCriteria(criteria);

        ExcelUtil.exportExcel(RegionGdp.class, exsitGdps);
    }

    /**
     * 跳转到统计页面
     */
    @GetMapping("/statcaseIndex")
//    @RequiresPermissions("gdp:regionGdp:statcaseIndex")
    public String statcaseIndex() {
        return "/gdp/regionGdp/statcaseIndex";
    }

    /**
     * 按申请事项统计
     */
    @GetMapping("/statByApplyItem")
    @ResponseBody
    public ResultVo statDocByRecordType(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime
    ) {

        if(StringUtil.isEmpty(startTime)){
            startTime="1911-01-01";
        }
        if(StringUtil.isEmpty(endTime)){
            endTime="9999-01-01";
        }

        List<Map<String, String>> maps = regionGdpService.statByApplyItem(startTime,endTime);
        List<Map<String, String>> _maps=new ArrayList<>();
        for(int i=0;i<maps.size();i++){
            Map<String, String> map=maps.get(i);
            String recordType=map.get("applyItem");
            if(!StringUtil.isEmpty(recordType)){
                String  recordName=DictUtil.keyValue("apply_item",recordType.toString());
                map.put("recordName", recordName);
                _maps.add(map);
            }
        }
        return ResultVoUtil.success(_maps);
    }


    /**
     * 审核员统计
     */
    @GetMapping("/statByCheckName")
    @ResponseBody
    public ResultVo statByCheckName(
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime
    ) {

        if(StringUtil.isEmpty(startTime)){
            startTime="1911-01-01";
        }
        if(StringUtil.isEmpty(endTime)){
            endTime="9999-01-01";
        }

        List<Map<String, String>> maps = regionGdpService.statByCheckName(startTime,endTime);
        List<Map<String, String>> _maps=new ArrayList<>();
        for(int i=0;i<maps.size();i++){
            Map<String, String> map=maps.get(i);
            String checkName=map.get("checkName");
            if(!StringUtil.isEmpty(checkName)){
                String  recordName=DictUtil.keyValue("apply_item",checkName.toString());
                map.put("checkName", checkName);
                _maps.add(map);
            }
        }
        return ResultVoUtil.success(_maps);
    }


    /**
     * 统计总数
     */
    @GetMapping("/statApplyCount")
    @ResponseBody
    public int statApplyCount() {
        int totalCount=0;
        totalCount = regionGdpService.statApplyCount();

        return totalCount;
    }


    /**
     * 统计技审通过总数
     */
    @GetMapping("/statApplyCountByTech")
    @ResponseBody
    public int statApplyCountByTech() {
        int totalCount=0;
        totalCount = regionGdpService.statApplyCountByTech();

        return totalCount;
    }



    /**
     * 统计审查轮次
     */
    @GetMapping("/statTotalAuditCount")
    @ResponseBody
    public int statTotalAuditCount() {
        int totalCount=0;
        totalCount = regionGdpService.statTotalAuditCount();

        return totalCount;
    }



    /**
     * 统计未审查轮次
     */
    @GetMapping("/statUnAuditCount")
    @ResponseBody
    public int statUnAuditCount() {
        int totalCount=0;
        totalCount = regionGdpService.statUnAuditCount();

        return totalCount;
    }


    /**
     * 按年份统计
     */
    @GetMapping("/statApplyItemByYear")
    @ResponseBody
    public ResultVo statApplyItemByYear(
            @RequestParam(required = false) String year
    ) {

        if(StringUtil.isEmpty(year)){
            Calendar cal = Calendar.getInstance();
            int _year = cal.get(Calendar.YEAR);
            year= String.valueOf(_year);
        }

        List<Map<String, String>> maps = regionGdpService.statApplyItemByYear(year);
        List<Map<String, String>> _maps=new ArrayList<>();
        for(int i=0;i<maps.size();i++){
            Map<String, String> map=maps.get(i);
            String month=map.get("month");
            if(!StringUtil.isEmpty(month)){
                map.put("month", month+"月");
                _maps.add(map);
            }
        }
        return ResultVoUtil.success(_maps);
    }

    /**
     * 按年份统计
     */
    @GetMapping("/statCheckNumsByYear")
    @ResponseBody
    public ResultVo statCheckNumsByYear(
            @RequestParam(required = false) String year
    ) {

        if(StringUtil.isEmpty(year)){
            Calendar cal = Calendar.getInstance();
            int _year = cal.get(Calendar.YEAR);
            year= String.valueOf(_year);
        }

        List<Map<String, String>> maps = regionGdpService.statCheckNumsByYear(year);
        List<Map<String, String>> _maps=new ArrayList<>();
        for(int i=0;i<maps.size();i++){
            Map<String, String> map=maps.get(i);
            String month=map.get("month");
            if(!StringUtil.isEmpty(month)){
                map.put("month", month+"月");
                _maps.add(map);
            }
        }
        return ResultVoUtil.success(_maps);
    }

    /**
     * 按年份统计
     */
    @GetMapping("/statCheckNumsAndNameByYear")
    @ResponseBody
    public ResultVo statCheckNumsAndNameByYear(
            @RequestParam(required = false) String year
    ) {

        if(StringUtil.isEmpty(year)){
            Calendar cal = Calendar.getInstance();
            int _year = cal.get(Calendar.YEAR);
            year= String.valueOf(_year);
        }

        List<Map<String, String>> maps = regionGdpService.statCheckNumsAndNameByYear(year);
        List<Map<String, String>> _maps=new ArrayList<>();
        for(int i=0;i<maps.size();i++){
            Map<String, String> map=maps.get(i);
            String month=map.get("month");
            if(!StringUtil.isEmpty(month)){
                map.put("month", month+"月");
                _maps.add(map);
            }
        }
        return ResultVoUtil.success(_maps);
    }


}
